<template>
  <div class="btn_warp" style="height:32px;width: 100%;padding-top: 5px;padding-bottom: 10px">
    <el-button type="success" plain class="btn_add" style="width:100px" @click="onAddItem">添加</el-button>
    <el-button type="danger" plain class="btn_delete" style="width: 100px" @click="onDeleteItem">删除</el-button>
    <el-button type="success" style="float: right;margin-right: 30px" @click.prevent="handleSearch">查询</el-button>
    <el-button type="success" style="float: right;margin-right: 5px" @click.prevent="handleClean">全部清空</el-button>
    <el-input v-model="search2" clearable placeholder="按设备品牌查询" style="float: right;width: 250px;margin-right: 15px"/>
    <el-input v-model="search1" clearable placeholder="按设备名称查询" style="float: right;width: 250px;margin-right: 15px"/>
  </div>
  <el-table @selection-change="handleSelsChange" :data="filterTableData.slice((currentPage-1)*pageSize,currentPage*pageSize)" stripe border style="width: 1285px;margin: 0 auto" max-height="472" height="472" :cell-style="{ textAlign: 'center' }">
    <el-table-column type="selection" width="40" >
    </el-table-column>
    <el-table-column fixed prop="" label="序号" width="70" :show-overflow-tooltip="true">
      <template #default="scope">
        {{scope.$index+1}}
      </template>
    </el-table-column>
    <el-table-column fixed prop="equipmentName" label="设备名称" width="200" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate">
              <el-input input-style="height:23px;" class="table-input" v-model="scope.row.equipmentName" maxlength="30" size="large"/>
            </span>
        <span v-else>{{ scope.row.equipmentName }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="equipmentBrand" label="设备品牌" width="150" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate">
              <el-input input-style="height:23px;" class="table-input" v-model="scope.row.equipmentBrand" maxlength="30" size="large"/>
            </span>
        <span v-else>{{ scope.row.equipmentBrand }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="equipmentType" label="设备型号" width="150" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate">
              <el-input input-style="height:23px" class="table-input" v-model="scope.row.equipmentType" maxlength="30" size="large"/>
            </span>
        <span v-else>{{ scope.row.equipmentType }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="equipmentPrice" label="设备价格(元)" width="130" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate">
              <el-input-number :precision="2" input-style="height:23px;" :min="0" :max="1000000" size="small" controls-position="right" class="table-input" v-model="scope.row.equipmentPrice"/>
            </span>
        <span v-else>{{ scope.row.equipmentPrice }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="equipmentQuantity" label="拥有数量(台)" width="130" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate">
              <el-input-number input-style="height:23px;" :min="0" :max="1000" size="small" controls-position="right" class="table-input" v-model="scope.row.equipmentQuantity"/>
            </span>
        <span v-else>{{ scope.row.equipmentQuantity }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="equipmentBuydate" label="购买日期" width="150" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate">
              <el-date-picker value-format="YYYY-MM-DD" size="small" style="width: 120px ;" v-model="scope.row.equipmentBuydate" type="date" placeholder="选择一个日期"></el-date-picker>
            </span>
        <span v-else>{{ scope.row.equipmentBuydate }}</span>
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" width="265" :show-overflow-tooltip="true">
      <template #default="scope">
        <el-button type="warning" round size="small" @click.prevent="updateRow(scope.$index)">修改</el-button>
        <el-button type="primary" round size="small" @click.prevent="saveRow(scope.$index,scope.row.equipmentId)">保存</el-button>
        <el-button type="danger" round size="small" @click.prevent="deleteRow(scope.row.equipmentId)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <div class="page_warp">
    <el-pagination  background @current-change="handleCurrentChange" v-model:page-size="pageSize" v-model:current-page="currentPage" layout="prev, pager, next , jumper" :total="filterTableData.length"></el-pagination>
  </div>
</template>

<script>
import { ElMessage,ElMessageBox } from 'element-plus'
import { ref,onMounted } from 'vue'
import {nanoid} from 'nanoid'
import {useRouter} from 'vue-router'
import axios from "axios"
export default {
  name: "HouseHold",
  setup(){
    const tableSels=ref([])
    const tableData = ref([])
    const pageSize=ref(10)
    const currentPage=ref(1)
    const router=useRouter()
    const search1=ref('')
    const search2=ref('')
    //条件过滤
    let filterTableData =ref([])

    //按条件进行查询
    function handleSearch(){
      console.log(search1)
      filterTableData.value=tableData.value.filter(
          (data) => data.equipmentName.toLowerCase().includes(search1.value.toLowerCase()) //匹配设备名称
              && data.equipmentBrand.toLowerCase().includes(search2.value.toLowerCase()) //匹配设备品牌
      )
    }
    //清空查询条件
    function handleClean(){
      search1.value=''
      search2.value=''
    }
    //选择添加事件
    function onAddItem(){
      tableData.value.push({
        equipmentId:nanoid(),   //设备id
        equipmentName:'',   //设备名称
        equipmentBrand: '',  //设备品牌
        equipmentType: '',  //设备型号
        equipmentPrice: 0,  //设备价格
        equipmentBuydate: formatDate(new Date()),  //购买日期
        equipmentQuantity:0,  //购买数量
        isUpdate:true,    //是否为编辑状态
        isAdd:true,    //是否为新增状态
      })
      currentPage.value=Math.ceil(tableData.value.length/pageSize.value)
    }
    //选择删除事件
    function onDeleteItem(){
      ElMessageBox.confirm('确认删除此记录吗？', '警告', {confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning',}).then(() => {
        tableSels.value.forEach((tableSel)=>{
          tableData.value.forEach((item,index)=>{
            if(item.equipmentId===tableSel.equipmentId){
              tableData.value.splice(index,1)
              //发送请求进行数据删除
              axios.get('http://localhost:8085/deleteEquipment',{
                params:{
                  equipmentId:item.equipmentId,   //住户id
                }
              }).then(
                  ()=>{
                    ElMessage({type:'success',message:'删除成功！'})
                  },
                  ()=>{
                    ElMessage({type:'error',message:'删除失败！'})
                    setTimeout(()=>{
                      router.go(0)
                    },500)
                  }
              )
            }
          })
        })
      }).catch(() => {
        ElMessage({type: 'info', message: '删除失败！',})
      })
    }
    //行修改事件
    function updateRow(index) {
      filterTableData.value[pageSize.value * (currentPage.value - 1) + index].isUpdate = true
    }
    //行保存事件
    function saveRow(index){
      let equipmentObj=filterTableData.value[pageSize.value*(currentPage.value-1)+index]
      if(!equipmentObj.isUpdate){
        ElMessage({message:'没有数据需要保存！'})
      }else if(equipmentObj.equipmentName === ''){  //判断姓名与物业地址是否为空
        ElMessage({message:'设备名称不能为空！'})
      }else if(equipmentObj.equipmentBuydate === ''){
        ElMessage({message:'购买日期不能为空！'})
      }else if(equipmentObj.isAdd){
        if(isRepeat(equipmentObj,index)) return
        //请求进行数据保存
        axios.get('http://localhost:8085/addEquipment',{
          params:{
            equipmentId:equipmentObj.equipmentId,   //设备id
            equipmentName:equipmentObj.equipmentName, //设备名称
            equipmentBrand:equipmentObj.equipmentBrand, //设备品牌
            equipmentType:equipmentObj.equipmentType, //设备型号
            equipmentPrice:equipmentObj.equipmentPrice, //设备价格
            equipmentBuydate:equipmentObj.equipmentBuydate, //购买日期
            equipmentQuantity:equipmentObj.equipmentQuantity, //拥有数量
          }
        }).then(
            ()=>{
              ElMessage({type:'success',message:'保存成功！'})
              //4.关闭输入框
              equipmentObj.isAdd=false
              equipmentObj.isUpdate=false
            },
            ()=>{
              ElMessage({type:'error',message:'保存失败！'})
            }
        )
      }else{
        if(isRepeat(equipmentObj,index)) return
        //请求进行数据修改
        axios.get('http://localhost:8085/updateEquipment',{
          params:{
            equipmentId:equipmentObj.equipmentId,   //设备id
            equipmentName:equipmentObj.equipmentName, //设备名称
            equipmentBrand:equipmentObj.equipmentBrand, //设备品牌
            equipmentType:equipmentObj.equipmentType, //设备型号
            equipmentPrice:equipmentObj.equipmentPrice, //设备价格
            equipmentBuydate:equipmentObj.equipmentBuydate, //购买日期
            equipmentQuantity:equipmentObj.equipmentQuantity, //拥有数量
          }
        }).then(
            ()=>{
              ElMessage({type:'success',message:'保存成功！'})
              //4.关闭输入框
              equipmentObj.isUpdate=false
            },
            ()=>{
              ElMessage({type:'error',message:'保存失败！'})
            }
        )
      }
    }
    //行删除事件
    function deleteRow(equipmentId){
      ElMessageBox.confirm('确认删除此记录吗？', '警告', {confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning',}).then(() => {
        tableData.value.forEach((item,index)=>{
          if(item.equipmentId===equipmentId){
            axios.get('http://localhost:8085/deleteEquipment',{
              async :false,
              params:{
                equipmentId:item.equipmentId,   //住户id
              }
            }).then(
                ()=>{
                  ElMessage({type:'success',message:'删除成功！'})
                  tableData.value.splice(index,1)
                },
                ()=>{
                  ElMessage({type:'error',message:'删除失败！'})
                }
            )
          }
        })
      }).catch(() => {
        ElMessage({type: 'info', message: '删除失败！',})
      })
    }
    //分页事件
    function handleCurrentChange(value){
      currentPage.value = value;
    }
    //处理多选
    const handleSelsChange=(sels)=>{
      tableSels.value=sels
    }
    onMounted(()=>{
      axios.get('http://localhost:8085/getEquipment').then(
          (response)=>{
            tableData.value=response.data
            filterTableData.value=response.data
          },
          ()=>{
          }
      )
    })
    //格式化Date类型
    function formatDate(val) {
      if(isNaN(val)) return ''
      const date = new Date(Number(val)); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      const Y = date.getFullYear() + "-";
      const M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
      const D = date.getDate() + " ";
      // const h = date.getHours() + ":";
      // const m = date.getMinutes() + ":";
      // const s = (date.getSeconds() < 10 ? "0" + (date.getSeconds()) : date.getSeconds());
      return Y + M + D;
    }
    //判断记录是否重复
    function isRepeat(Obj,index){
      let tip=0
      tableData.value.forEach((item,indexx)=>{
        if(Obj.equipmentName==item.equipmentName && Obj.equipmentBrand==item.equipmentBrand && Obj.equipmentType==item.equipmentType && (pageSize.value*(currentPage.value-1)+index)!=indexx){
          tip=1
        }
      })
      if(tip==1){
        ElMessage({type:'error',message:'保存失败,该设备信息记录已存在！'})
        return true
      }else{
        return false
      }
    }

    return{
      tableSels,
      tableData,
      filterTableData,
      search1,
      search2,
      pageSize,
      currentPage,
      formatDate,
      onAddItem,
      onDeleteItem,
      updateRow,
      saveRow,
      deleteRow,
      handleCurrentChange,
      handleSelsChange,
      isRepeat,
      handleSearch,
      handleClean
    }
  }
}
</script>

<style scoped>
  .el-table{
    /*padding: 20px 20px 20px 20px;*/
  }
  .page_warp{
    width: 600px;
    margin: 5px auto;
    height: 40px;
  }
  .el-pagination{
    margin-right: 50px;
  }
  .demo-date-picker {
    display: flex;
    width: 100%;
    padding: 0;
    flex-wrap: wrap;
  }

  .demo-date-picker .block {
    padding: 30px 0;
    text-align: center;
    border-right: solid 1px var(--el-border-color-base);
    flex: 1;
  }
  .demo-date-picker .block:last-child {
    border-right: none;
  }
  .demo-date-picker .demonstration {
    display: block;
    color: var(--el-text-color-secondary);
    font-size: 14px;
    margin-bottom: 20px;
  }
  .el-input-number--small{
    width: 100px;
  }
</style>